package com.duoec.dw.lineage.service.analyser.from;

import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLWithSubqueryClause;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import org.springframework.stereotype.Service;

@Service
public class SQLWithSubqueryClauseAnalyser extends BaseTableSourceAnalyser<SQLWithSubqueryClause> {

    /**
     * 获取当前类处理的类型
     *
     * @return SQLTableSource子类类型
     */
    @Override
    public Class<SQLWithSubqueryClause> getTableSourceType() {
        return SQLWithSubqueryClause.class;
    }

    /**
     * 解析 from
     *
     * @param withSubQuery  with-in语句
     * @param tableLineages 父级查询的win-in结果，永远为空
     * @return 当前select脚本的血缘关系
     */
    @Override
    public MultiTableLineageDto analyse(SQLWithSubqueryClause withSubQuery, MultiTableLineageDto tableLineages) {
        MultiTableLineageDto withAsTableLineages = new MultiTableLineageDto();
        if (withSubQuery == null) {
            return withAsTableLineages;
        }

        withSubQuery.getEntries().forEach(entry -> {
            String aliasName = entry.getAlias();
            if (withAsTableLineages.containsTableName(aliasName)) {
                return;
            }
            SQLSelect subQuery = entry.getSubQuery();
            TableLineageDto tableLineageDto = hiveAnalyser.analyseQuery(subQuery.getQuery(), null);
            tableLineageDto.setAlias(aliasName);
            withAsTableLineages.add(tableLineageDto);
        });
        return withAsTableLineages;
    }
}
